package com.jixiantubu.luntan;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.example.jixiantubu.R;
import com.example.jixiantubu.R.anim;
import com.example.jixiantubu.R.id;
import com.example.jixiantubu.R.layout;
import com.example.jixiantubu.R.string;
import com.example.jixiantubu.R.style;
import com.jixiantubu.util.Config;
import com.jixiantubu.util.CustomProgressDialog;
import com.jixiantubu.util.MyApplication;
import com.jixiantubu.util.StringUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class WodeTupian_Write extends Activity implements OnClickListener{
	private Dialog dialog;// 获取图片的弹出框
	File file;//文件
	LinearLayout ll_imgs;//图片布局
	List<String> imgs_path;// 上传图片的路径
	ImageView addGoodsPic;//添加图片
	int index = -1;// 记录要替换的图片 当为-1时 为新增
	String tempImgName;//图片姓名
	String flag="false";
	ImageView backImageView;//返回上一级
	EditText tittleEditText;// 定义一个文本输入框
	TextView savetTextView;// 用来显示剩余字数
	Intent intent;
	String phname;
	CheckBox allsee;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = this.getWindow();
		window.requestFeature(window.FEATURE_NO_TITLE);
		setContentView(R.layout.wode_tupian_write);
		initData();
		initViews();
		
	}

	private void initData() {
		imgs_path = new ArrayList<String>();//初始化图片路径 定义成一个集合
		
	}
	
	private void Tools() {
		phname=tittleEditText.getText().toString();
	}

	private void initViews() {
		ll_imgs = (LinearLayout) findViewById(R.id.luntan_wode_tupian);
		addGoodsPic = (ImageView) findViewById(R.id.luntan_wode_tupiantianjia);
		addGoodsPic.setOnClickListener(this);
		//对标题栏和内容栏进行初始化
		tittleEditText = (EditText) findViewById(R.id.luntan_wode_tupian_tianjiabiaoti);
		allsee=(CheckBox) findViewById(R.id.select_all2);

		backImageView = (ImageView) findViewById(R.id.luntan_wode_tupian_write_back);
		savetTextView = (TextView) findViewById(R.id.luntan_wode_tupian_write_save);
		backImageView.setOnClickListener(this);
		savetTextView.setOnClickListener(this);
		allsee.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1){
					flag="false";			
				}else{
					flag="true";
				}
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.luntan_wode_tupian_write_back:
			finish();
			break;
		case R.id.luntan_wode_tupiantianjia:// 点击添加商品图片
			index = -1;
			showPhotoDialog();
			break;
		case R.id.openCamera:// 打开相机
			openCamera();
			break;
		case R.id.openPhones:// 打开图库
			openPhones();
			break;
		case R.id.cancel:// 取消
			dialog.cancel();
			break;
		case R.id.luntan_wode_tupian_write_save:
			//信息完整性验证后调用提交
			//if(checkGoodsParameter())
				uploadGoods();
				
			/*intent=new Intent(WodeTupian_Write.this,
					WodeTupianActivity.class);
			startActivity(intent);*/
			break;
		default:
			break;
		}
		
	}
	private void openCamera() {
		dialog.dismiss();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		tempImgName = StringUtils.getImageSaveName();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
				WodeTupian_Write.this.getExternalCacheDir(), tempImgName)));

		startActivityForResult(intent, Config.REQUEST_CODE_CAMERA);
	}
	private void openPhones() {
		dialog.dismiss();
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, Config.REQUEST_CODE_OPENPICS);
	}

	void addImageView(Uri uri) {
		String img_path = getExternalCacheDir() + File.separator + tempImgName;
		if (index == -1) {
			final ImageView imageView = new ImageView(this);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					addGoodsPic.getWidth(), addGoodsPic.getHeight());
			params.setMargins(20, 0, 0, 0);
			imageView.setLayoutParams(params);
			imageView.setImageURI(uri);
			final int n = imgs_path.size();// 当前商品图片数量
			imageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(final View v) {
					new AlertDialog.Builder(WodeTupian_Write.this)
							.setNegativeButton(R.string.cancle,
									new DialogInterface.OnClickListener() {

										// 取消
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									})
							.setNeutralButton(
									getResources().getString(R.string.edit),
									new DialogInterface.OnClickListener() {
										// 编辑
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();
											showPhotoDialog();
											index = ll_imgs.indexOfChild(v);

										}
									})
							.setPositiveButton(R.string.delete,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// 删除
											dialog.dismiss();
											removeImageView(v);
										}
									}).show();

				}
			});
			ll_imgs.addView(imageView, n);
			//添加图片路径
			imgs_path.add(img_path);
			
		} else {
			ImageView imageView = (ImageView) ll_imgs.getChildAt(index);
			imageView.setImageURI(uri);
			imgs_path.set(index, img_path);
		}

	}

	void removeImageView(View v) {
		imgs_path.remove(ll_imgs.indexOfChild(v));
		StringUtils.showToast(WodeTupian_Write.this,
				"" + ll_imgs.indexOfChild(v));
		ll_imgs.removeView(v);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1.5);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		tempImgName = StringUtils.getImageSaveName();
		intent.putExtra("output",
				Uri.fromFile(new File(this.getExternalCacheDir(), tempImgName)));
		startActivityForResult(intent, Config.REQUEST_CODE_ZOOM);
	}
	private void showPhotoDialog() {
		View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog11111,
				null);
		view.findViewById(R.id.openCamera).setOnClickListener(this);
		view.findViewById(R.id.openPhones).setOnClickListener(this);
		view.findViewById(R.id.cancel).setOnClickListener(this);
		dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
		dialog.setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
		Window window = dialog.getWindow();
		// 设置显示动画
		window.setWindowAnimations(R.style.main_menu_animstyle);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0;
		wl.y = getWindowManager().getDefaultDisplay().getHeight();
		// 以下这两句是为了保证按钮可以水平满屏
		wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
		wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		// 设置显示位置
		dialog.onWindowAttributesChanged(wl);
		// 设置点击外围解散
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case Config.REQUEST_CODE_CAMERA:
				File file = new File(this.getExternalCacheDir(), tempImgName);
				startPhotoZoom(Uri.fromFile(file));
				break;
			case Config.REQUEST_CODE_OPENPICS:
				Uri uri = data.getData();
				startPhotoZoom(uri);
				break;

			case Config.REQUEST_CODE_ZOOM:
				File file2 = new File(getExternalCacheDir(), tempImgName);
				addImageView(Uri.fromFile(file2));
				break;
	
			default:
				break;
			}
		}
	}
	boolean checkGoodsParameter(){
		//没有选择商品图片的
		if(tittleEditText.getText().length()==0){
			StringUtils.showToast(this, Config.ERROR_NO_TITLE);
			tittleEditText.requestFocus();
			return false;
		}else if (tittleEditText.getText().length()<1) {
			StringUtils.showToast(this, Config.ERROR_TITLE_TOSHORT);
			tittleEditText.requestFocus();
			return false;
		}
		return true;
	}
	
	
	
	private void uploadGoods() {
		Tools();
		final CustomProgressDialog pd = new CustomProgressDialog(
				WodeTupian_Write.this, "正在拼命加载数据,请稍等！", R.anim.frame);
		pd.show();
		RequestParams params = new RequestParams();
		//params.addBodyParameter("key","5");
		params.addBodyParameter("phname",phname);
		params.addBodyParameter("user_id",
				MyApplication.user_id);
		params.addBodyParameter("flag",flag);
		System.out.println(phname+"--------"+MyApplication.user_id+"--------"+5+flag);
		//获取图片的总数i   放到文件内，一并传到web端
		for (int i = 0; i < imgs_path.size(); i++) {
			params.addBodyParameter(""+i, new File(imgs_path.get(i)));
			Log.e("图片路径",imgs_path.get(i));
		}
		String uploadHost="http://" + MyApplication.getIP()
				+ ":8080/Jinnang/Tupian_jieshou";
		MyApplication.httpclient.configSoTimeout(5000);
		MyApplication.httpclient.send(HttpMethod.POST, uploadHost,
				params, new RequestCallBack<String>() {
					@Override
					public void onStart() {
						
					}

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						// 上传中
						System.out.println("上传中  ");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// 上传成功，这里面的返回值，就是服务器返回的数据
						// 使用 String result = responseInfo.result 获取返回值
						System.out.println("上传成功");
						StringUtils.showToast(WodeTupian_Write.this, "图片上传成功！");
						System.out.println(responseInfo.result);
						pd.dismiss();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// 上传失败
						pd.dismiss();
						StringUtils.showToast(WodeTupian_Write.this, "图片上传失败，请检查网络！");
						System.out.println("上传失败  ");
					}
				});
	}
}
